package org.gm.runnable;

import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.geth.Geth;

import java.math.BigInteger;
import java.util.Map;

public class MinerRunnable implements Runnable {
    private boolean running = true;

    private final Geth geth;
    private final Admin admin;

    public MinerRunnable(Geth geth, Admin admin) {
        this.geth = geth;
        this.admin = admin;
    }

    @Override
    public void run() {
        boolean flag = false;

        try {
            while (running) {
                Map<String, Map<BigInteger, Transaction>> pending =
                        admin.txPoolContent().send().getResult().getPending();

                if (pending.size() != 0 && !flag) {
                    geth.minerStart(1).send();
                    flag = true;
                } else if (pending.size() == 0) {
                    geth.minerStop().send();
                    flag = false;
                    Thread.sleep(1000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        running = false;
    }
}
